<template>
  <!-- 存放账号信息下的个人资料 -->
  <div class="personal-data-container">
    <el-card class="personal-data-card">
      <!-- 1.个人资料栏 -->
      <el-tabs type="border-card">
        <el-tab-pane label="基本信息">
          <el-form
            :model="basicInfoForm"
            ref="basicInfoForm"
            label-width="120px"
            class="basic-info-form"
            label-position="left"
            :rules="basicInfoFormRules"
          >
            <el-row type="flex" align="middle">
              <el-col :span="6">
                <el-form-item label="头像" style="height: 80px">
                  <el-avatar
                    :size="90"
                    fit="cover"
                    :src="basicInfoForm.avatarUrl"
                    style="font-size: 18px"
                    >User</el-avatar
                  >
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <!-- 头像修改，头像应该根据用户的id进行提交 -->
                <!-- TODO:下面的action地址需要修改 -->
                <el-upload
                  class="upload-avatar"
                  :limit="1"
                  :show-file-list="false"
                  accept=".jpg,.jpeg,.png"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess"
                  :on-error="handleAvatarError"
                  :http-request="uploadAvatar"
                  action="#"
                >
                  <!-- 按钮与提示信息 -->
                  <el-button size="small" type="primary" icon="el-icon-upload"
                    >点击上传头像</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png/jpeg文件，且不超过500KB
                  </div>
                </el-upload></el-col
              >
            </el-row>
            <el-divider style="margin-top: 10px" class="information-divider"
              >基本信息</el-divider
            >
            <el-row>
              <el-col :span="24">
                <el-form-item label="用户昵称" prop="nickName">
                  <!-- trim修饰符消除前后空格 -->
                  <el-input
                    v-model.trim="basicInfoForm.nickName"
                    placeholder="请输入新的昵称"
                    type="text"
                    maxlength="25"
                    show-word-limit
                    spellcheck="false"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 禁止修改账号 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="用户账号(ID)">
                  <el-input
                    v-model="basicInfoForm.userName"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 性别 -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="basicInfoForm.gender">
                    <el-radio label="男" :border="true" size="medium"
                      >男</el-radio
                    >
                    <el-radio label="女" :border="true" size="medium"
                      >女</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <!-- 隐私是否显示 -->
              <el-col :span="6">
                <el-form-item prop="genderShow">
                  <el-checkbox v-model="basicInfoForm.genderShow"
                    >在个人主页展示</el-checkbox
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 年龄 -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="年龄" prop="age">
                  <el-input-number
                    v-model.number="basicInfoForm.age"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="ageShow">
                  <el-checkbox v-model="basicInfoForm.ageShow"
                    >在个人主页展示</el-checkbox
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <!-- qq -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="QQ" prop="qq">
                  <el-input v-model.trim="basicInfoForm.qq"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="qqShow">
                  <el-checkbox v-model="basicInfoForm.qqShow"
                    >在个人主页展示</el-checkbox
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 微信 -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="微信" prop="WeChat">
                  <el-input v-model.trim="basicInfoForm.WeChat"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="WeChatShow">
                  <el-checkbox v-model="basicInfoForm.WeChatShow"
                    >在个人主页展示</el-checkbox
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 邮箱 -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model.trim="basicInfoForm.email"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="emailShow">
                  <el-checkbox v-model="basicInfoForm.emailShow"
                    >在个人主页展示</el-checkbox
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 配置个人偏好的信息 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="个人偏好" prop="interestedTags">
                  <el-select
                    v-model="basicInfoForm.interestedTags"
                    multiple
                    :multiple-limit="7"
                    placeholder="请选择您感兴趣的内容，我们将为你推荐相关内容"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="(item, index) in tags"
                      :key="index"
                      :label="item.tagName"
                      :value="item.tagId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 个人简介 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="个人简介" prop="introduce">
                  <!-- spellcheck关闭拼写检查 -->
                  <el-input
                    type="textarea"
                    spellcheck="false"
                    v-model="basicInfoForm.introduce"
                    :autosize="{ minRows: 4, maxRows: 4 }"
                    maxlength="100"
                    show-word-limit
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitBasicInfoForm('basicInfoForm')"
                size="medium"
                icon="el-icon-upload2"
                >更新</el-button
              >
              <el-button
                @click="resetBasicInfoForm('basicInfoForm')"
                size="medium"
                icon="el-icon-refresh"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="教育信息">教育信息</el-tab-pane>
        <el-tab-pane label="工作信息">工作信息</el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script lang="ts">
import { Component, Vue,  } from "vue-property-decorator";
import {
  getWholeUserInfo,
  getAllTags,
  updateUserInfo,
  getQiNiuToken,
  uploadFileToQiNiu,
  uploadAvatarToDB,
} from "@/apis/apis";
@Component({
  name: "personalData",
})
export default class personalData extends Vue {
  // 七牛云的token
  qiNiuToken: string = "";
  // 个人基本信息
  basicInfoForm: {
    avatarUrl?: string;
    nickName: string;
    userName: string;
    gender: string;
    genderShow: boolean;
    age?: number;
    ageShow?: boolean;
    qq?: string;
    qqShow?: boolean;
    WeChat?: string;
    WeChatShow?: boolean;
    email?: string;
    emailShow?: boolean;
    introduce?: string;
    interestedTags?: number[];
  } = {
    avatarUrl: this.$store.state.avatarUrl,
    nickName: "",
    userName: "",
    gender: "男",
    genderShow: false,
    age: 0,
    ageShow: false,
    qq: "",
    qqShow: false,
    WeChat: "",
    WeChatShow: false,
    email: "",
    emailShow: false,
    introduce: "",
    interestedTags: [],
  };
  // 所有的标签的数据
  tags: any = [{ tagId: 1, tagName: "测试" }];
  // 请求用户的所有信息
  mounted() {
    // 获取头像上传的token
    this.getUploadToken();
    // 获取所有的标签
    this.getAllTagsForForm();
    // 获取用户信息
    this.getUserInformation();
  }
  // 获取七牛云的token
  getUploadToken() {
    getQiNiuToken()
      .then((res) => {
        if (res.data.code === "200") {
          this.qiNiuToken = res.data.data;
        } else {
          this.$message.error("获取token失败!");
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  // 上传用户的头像信息
  uploadAvatar(e: any) {
    var imgUrl: string = "";
    var formData = new FormData();
    formData.append("myFileName", e.file);
    // 后端上传图片到七牛云
    uploadFileToQiNiu(this.qiNiuToken, formData)
      .then((res) => {
        if (res.data.code === "200") {
          imgUrl = res.data.data;
          this.basicInfoForm.avatarUrl = imgUrl;
          // 更新vuex中的头像
          this.$store.commit("setAvatarUrl", imgUrl);
          // 拿到头像的地址后将头像的地址传输给后端
          uploadAvatarToDB(imgUrl)
            .then((res) => {
              if (res.data.code === "200") {
                this.$message.success("头像上传成功!");
                // 更新头像后向服务器发送请求更新数据
              } else {
                this.$message.error("头像上传失败!");
              }
            })
            .catch((err) => {
              console.log(err);
            });
          this.$message.success("头像上传成功!");
          // 更新头像后向服务器发送请求更新数据
        } else {
          this.$message.error("头像上传失败!");
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  // 获取用户的详细信息
  getUserInformation() {
    getWholeUserInfo()
      .then((res) => {
        // console.log(res.data);
        let resData = res.data.data;
        if (res.data.code === "200") {
          // 注意字段名核对正确
          this.basicInfoForm.nickName = resData.nickName;
          this.basicInfoForm.gender = resData.sex;
          this.basicInfoForm.avatarUrl = resData.avatar;
          console.log(this.basicInfoForm.avatarUrl);
          
          this.basicInfoForm.email = resData.email;
          this.basicInfoForm.age = resData.age;
          this.basicInfoForm.introduce = resData.introduction;
          this.basicInfoForm.userName = resData.userName;
          this.basicInfoForm.qq = resData.qq;
          this.basicInfoForm.WeChat = resData.weChat;
          // 取出所有的id
          this.basicInfoForm.interestedTags = resData.tags.map(
            (item: any) => item.tagId
          );
          // 数据展示状态
          this.basicInfoForm.genderShow = resData.showSex === "1";
          this.basicInfoForm.ageShow = resData.showAge === "1";
          this.basicInfoForm.qqShow = resData.showQQ === "1";
          this.basicInfoForm.WeChatShow = resData.showWeChat === "1";
          this.basicInfoForm.emailShow = resData.showEmail === "1";
          this.$store.commit("setAvatarUrl", this.basicInfoForm.avatarUrl);
        } else {
          this.$message.error("获取用户信息失败!");
        }
      })
      .catch((err) => {
        this.$message.error("获取用户信息失败!");
        console.log(err);
      });
  }

  // 兴趣标签选择
  getAllTagsForForm() {
    getAllTags()
      .then((res) => {
        let resData = res.data.data;
        // 默认标签清空
        this.tags = [];
        resData.forEach((item: any) => {
          this.tags.push({
            tagId: item.tagId,
            tagName: item.tagName,
          });
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }
  // 允许的图片类型
  acceptAvatarType: string[] = ["jpeg", "png", "jpg"];
  // 头像上传前的检查
  beforeAvatarUpload(file: any): boolean {
    let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
    if (!this.acceptAvatarType.includes(fileType)) {
      this.$message.error("上传头像图片只能是 JPG/PNG/JPEG 格式!");
      return false;
    }
    // 大小小于500kb
    if (file.size / 1024 / 1024 > 0.5) {
      this.$message.error("上传头像图片大小不能超过 500KB!");
      return false;
    }

    return true;
  }
  // 头像上传成功后重新请求信息
  handleAvatarSuccess(res: any, file: any) {
    // res为服务器返回的数据
    if (res.code === 200) {
      this.$message.success("头像上传成功!");
      this.basicInfoForm.avatarUrl = URL.createObjectURL(file.raw);
      console.log(res.data);
      // 更新头像
      // 更新头像后向服务器发送请求更新数据
      // this.submitBasicInfoForm("basicInfoForm");
      this.$message.success("头像更新成功!");
    } else {
      this.$message.error("头像上传失败!请重试!");
    }
  }

  // 头像上传失败
  handleAvatarError() {
    this.$message.error("头像上传失败!请重试!");
  }

  //   表单验证规则，trigger是触发方式,blur是失去焦点时触发
  basicInfoFormRules: any = {
    nickName: [
      {
        min: 1,
        max: 25,
        message: "昵称长度在 1 至 25 个字符",
        trigger: "blur",
      },
    ],
    age: [{ type: "number", message: "年龄必须为数字", trigger: "blur" }],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
  };

  submitBasicInfoForm(formName: string) {
    (this.$refs[formName] as any).validate((valid: any) => {
      if (valid) {
        updateUserInfo({
          avatar: this.basicInfoForm.avatarUrl,
          email: this.basicInfoForm.email,
          introduction: this.basicInfoForm.introduce,
          nickName: this.basicInfoForm.nickName,
          qq: this.basicInfoForm.qq,
          sex: this.basicInfoForm.gender,
          showAge: this.basicInfoForm.ageShow ? "1" : "0",
          showEmail: this.basicInfoForm.emailShow ? "1" : "0",
          showSex: this.basicInfoForm.genderShow ? "1" : "0",
          showWeChat: this.basicInfoForm.WeChatShow ? "1" : "0",
          showQQ: this.basicInfoForm.qqShow ? "1" : "0",
          tags: this.basicInfoForm.interestedTags,
          weChat: this.basicInfoForm.WeChat,
        })
          .then((res) => {
            let resData = res.data;
            if (resData.code === "200") {
              this.$message.success("更新成功!即将刷新");
              // 更新Vuex中的数据
              this.$store.commit("setNickName", this.basicInfoForm.nickName);
              this.$store.commit("avatarUrl", this.basicInfoForm.avatarUrl);
              setTimeout(() => {
                window.location.reload();
              }, 2000);
            } else {
              this.$message.error("更新失败!");
            }
          })
          .catch((err) => {
            this.$message.error("更新失败!");
            console.log(err);
            // console.log("this is error from updateUserInfo personalData");
          });
      } else {
        console.log("error submit!!");
        return false;
      }
    });
  }
  // 重置表单
  resetBasicInfoForm(formName: string) {
    (this.$refs[formName] as any).resetFields();
  }
}
</script>

<style lang="scss" scoped>
.personal-data-container {
  width: 100%;
  height: 100%;
  .personal-data-card {
    width: 100%;
    height: 100%;
    .basic-info-form {
      ::v-deep(.information-divider) {
        margin-top: 10px;
      }
    }
  }
}
</style>